﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Security.Cryptography.X509Certificates;
using Newtonsoft.Json;
using Cloud.Core.Model;
using Cloud.Core.Response;
using Cloud.Core.AuthUser;
using Microsoft.EntityFrameworkCore.Internal;
using Cloud.Core.Bizlogic;
using Cloud.Core.ModelSearch;
using System.Threading;

namespace Cloud.Core.Controllers
{
    /// <summary>
    /// 传感器管理
    /// </summary> 
    [Route("api/v1/[controller]")]
    [ApiController]
    public class SensorController : ControllerBase
    {
        private readonly CloudDataBase _context;
        private readonly ModOperate.Mod _thisModel = ModOperate.Mod.MBasicInfo;
        public SensorController(CloudDataBase context)
        {
            _context = context;
        }

        #region base     
        #region 传感器选型
        /// <summary>
        /// 秤选传感器
        /// </summary>
        /// by zhengyb 2020-10-14
        /// <returns></returns>
        [Route("modelsensor")]
        [HttpPost]
        public async Task<JsonResponse<DataList<Sensor>>> modelsensor([FromHeader] string Authorization, [FromBody] sSensor sSensor)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<DataList<Sensor>>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //} 
            response.Data = new DataList<Sensor>();
            if (string.IsNullOrEmpty(sSensor.flow))
            {
                response.Msg = "流量不允许为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            if (string.IsNullOrEmpty(sSensor.speed) || sSensor.speed == "0")
            {
                response.Msg = "速度不能为空且不为0！";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            if (string.IsNullOrEmpty(sSensor.fulcrum) || sSensor.fulcrum == "0")
            {
                response.Msg = "支点不能为空且不为0！";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            if (string.IsNullOrEmpty(sSensor.width))
            {
                response.Msg = "托轨间距不能为空！";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            if (string.IsNullOrEmpty(sSensor.count))
            {
                response.Msg = "托轨数量不能为空！";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }

            var flow = Convert.ToDouble(sSensor.flow) / 3.6;
            var speed = Convert.ToDouble(sSensor.speed);
            var fulcrum = Convert.ToInt32(sSensor.fulcrum);
            var width = Convert.ToDouble(sSensor.width) / 1000;
            var count = Convert.ToInt32(sSensor.count);
            double calcWeight = (flow * width * count) / (fulcrum * speed);

            string calcWeightstr = calcWeight.ToString("f2");
            if (calcWeight > 2000)
            {
                response.Msg = "超过最大载荷，请重新填写 ！";
                response.Status = ResponseStatus.ProcessFail;
                return response;
            }
            //int[] weightArr = new int[7] { 50, 100, 200, 300, 500, 1000, 2000 };
            //int maxWeight = 0;
            //for (int i = 0; i < weightArr.Length; i++)
            //{
            //    var item = weightArr[i];
            //    if (n < item)
            //    {
            //        var newNum = item * 0.8;
            //        if (i >= 4)
            //        {
            //            newNum = item * 0.85;
            //        }
            //        if (n >= newNum)
            //        {
            //            maxWeight = weightArr[i + 1];
            //            break;
            //        }
            //        else
            //        {
            //            maxWeight = item;
            //            break;
            //        }
            //    }
            //}

            var listQuery = _context.Sensor.Where(t => t.enabled == 1 && t.ratedLoad >= calcWeight);
            if (calcWeight < 30)
            {
                listQuery= listQuery.Where(t => t.ratedLoad <= 60);
            }
            else
            {
                listQuery = listQuery.Where(t => t.ratedLoad <= calcWeight * 2);
            }
            if (!string.IsNullOrEmpty(sSensor.outputSignal))
            {
                listQuery = listQuery.Where(t => t.outputSignal == sSensor.outputSignal);
            }
            string tj = "";
            var newtj = listQuery.Select(t => t.ratedLoad).Distinct().OrderBy(x => x).ToArray();
            if (newtj.Length > 0)
            {
                tj = string.Join(",", newtj);
            }

            response.Data.Total = await listQuery.CountAsync().ConfigureAwait(false);
            var list = await listQuery
                   .OrderBy(t => t.Name)
                   .ThenBy(t => t.CreateDate)
                   .ToArrayAsync()
                   .ConfigureAwait(false);
            response.Data.Count = list.Length;
            response.Data.List = list;

            response.Msg = "理论载荷：" + calcWeightstr + "kg，推荐载荷" + tj + "kg";
            response.Status = ResponseStatus.Success;
            return response;
        }

        #endregion  

        #region 获取传感器信息
        /// <summary>
        /// 获取分页信息
        /// </summary>
        /// <returns></returns>
        [Route("GetList")]
        [HttpPost]
        public async Task<JsonResponse<DataList<Sensor>>> GetList([FromHeader] string Authorization, sField sPage)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser<DataList<Sensor>>(_thisModel, ModOperate.Operate.Search, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}
            response.Data = new DataList<Sensor>();
            var listQuery = _context.Sensor.Where(t => 1 == 1);
            //if (!string.IsNullOrEmpty(sPage.Field1))
            //{
            //    listQuery = listQuery.Where(t => t.Code.Contains(sPage.Field1) || t.Value.Contains(sPage.Field1));
            //}
            //if (!string.IsNullOrEmpty(sPage.Field2))
            //{
            //    listQuery = listQuery.Where(t => t.Enabled == Convert.ToInt32(sPage.Field2));
            //}
            response.Data.Total = await listQuery.CountAsync().ConfigureAwait(false);
            var list = await listQuery
                   .OrderBy(t => t.CreateDate)
                   .ToArrayAsync()
                   .ConfigureAwait(false);
            response.Data.Count = list.Length;
            response.Data.List = list;
            response.Status = ResponseStatus.Success;
            response.Msg = "查询成功";

            return response;
        }
        #endregion

        #region 传感器添加
        /// <summary>
        /// 传感器添加
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [Route("SensorAdd")]
        [HttpPost]
        public async Task<JsonResponse> SensorAdd([FromHeader] string Authorization, Sensor entity = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }

            var data = await _context.Sensor.FirstOrDefaultAsync(t => t.Id == entity.Id).ConfigureAwait(false);
            if (data != null)
            {
                response.Msg = "添加失败,该传感器已存在";
                response.Status = ResponseStatus.MultipleData;
                return response;
            }
            var arr = _context.Sensor.Select(t => t.Id).ToArray();


            _context.Set<Sensor>().Add(entity);
            //int num = await _context.SaveChangesAsync().ConfigureAwait(false);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "传感器添加成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "添加失败";
                response.Status = ResponseStatus.ParameterError;
            }
            string et = response.Msg + "-实体内容:" + new Helper().ObjectToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));


            return response;
        }
        #endregion

        #region 传感器编辑
        /// <summary>
        /// 传感器编辑 
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        [Route("SensorUpdate")]
        public async Task<JsonResponse> SensorUpdate([FromHeader] string Authorization, Sensor entity = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (entity == null)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
                return response;
            }
            var dataCount = _context.Set<Sensor>().Where(c => c.Id == entity.Id).Count();

            //var data = await _context.Sensor.FirstOrDefaultAsync(t => t.Id == entity.Id).ConfigureAwait(false);
            if (dataCount == 0)
            {
                response.Msg = "修改失败,数据不存在";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            _context.Set<Sensor>().Update(entity);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "传感器修改成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "修改失败";
                response.Status = ResponseStatus.ProcessFail;
            }
            string et = response.Msg + "-修改数据:" + new Helper().objToJson(entity);
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, et), RouteData.Values.Values.Join(","));

            return response;
        }

        #endregion

        #region 传感器删除
        /// <summary>
        /// 传感器删除 
        /// </summary>
        /// <param name="aaa"></param>
        /// <returns></returns>
        [HttpGet]
        [Route("SensorDel")]
        public async Task<JsonResponse> SensorDel([FromHeader] string Authorization, string ids = null)
        {
            var _character = Online.GetLoginInfo(Authorization);
            var response = Online.AuthUser(_thisModel, ModOperate.Operate.Add, _character);
            //if (response.Status != ResponseStatus.Success)
            //{
            //    return response;
            //}

            if (ids.Length == 0)
            {
                response.Msg = "参数为空";
                response.Status = ResponseStatus.ParameterError;
            }

            string[] arr = ids.TrimEnd(',').Split(',');
            string[] barr = new string[arr.Length];
            for (int i = 0; i < arr.Length; i++)
            {
                barr[i] = arr[i];
            }
            var Sensors = _context.Sensor.Where(c => barr.Contains(c.Id));

            var dataCount = Sensors.Count();
            if (dataCount == 0)
            {
                response.Msg = "数据不存在,不允许删除";
                response.Status = ResponseStatus.NullData;
                return response;
            }
            string delArr = new Helper().objToJson(Sensors);

            _context.Sensor.RemoveRange(Sensors);
            int num = _context.SaveChanges();
            if (num > 0)
            {
                response.Msg = "传感器删除成功";
                response.Status = ResponseStatus.Success;
            }
            else
            {
                response.Msg = "传感器删除失败";
                response.Status = ResponseStatus.ParameterError;
            }
            delArr = response.Msg + "-删除集合:" + delArr;
            await new LoggerWriteen().writeAsync(new Log(Log.OperateType.操作, delArr), RouteData.Values.Values.Join(","));

            return response;
        }
        #endregion        
        #endregion
    }
}
